# -*- coding: utf-8 -*-

from django.db import models
from django.core.urlresolvers import reverse
from django.db.models import permalink
from books.fields import ThumbnailImageField


class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()

    class Meta:
        ordering = ["-name"]

    def __unicode__(self):
        return self.name

    # @permalink
    # def get_absolute_url(self):
    #     return  reverse('publisher_detail', [], kwargs={'pk': self.pk})
        ##return reverse(viewname='publisher_detail', args=(), kwargs={'pk': self.pk})


class MaleManager(models.Manager):
    def get_queryset(self):
        return super(MaleManager, self).get_query_set().filter(sex='M')


class FemaleManager(models.Manager):
    def get_queryset(self):
        return super(FemaleManager, self).get_query_set().filter(sex='F')


class Author(models.Model):
    salutation = models.CharField(verbose_name='write class', max_length=10)
    name = models.CharField(max_length=200)
    sex = models.CharField(max_length=1, choices=(('M', u'男'), ('F', u'女')))
    email = models.EmailField()
    #headshot = models.ImageField(upload_to='author_headshots')
    headshot = ThumbnailImageField(upload_to='author_headshots')
    objects = models.Manager()
    men = MaleManager()
    women = FemaleManager()

    def __unicode__(self):
        return self.name

    ##@permalink
    def get_absolute_url(self):
        return reverse('book:author_detail', kwargs={'pk': self.pk})



class BookManager(models.Manager):
    def book_count(self, book_name):
        return self.filter(title__icontains=book_name).count()


class Book(models.Model):
    title = models.CharField(max_length=100, help_text="new book's title")
    authors = models.ManyToManyField('Author')
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()
    objects = BookManager()

    def __unicode__(self):
        return self.title

    def authors_list(self):
        """
        return 'author1 author2 ...'
        """
        # authors = []
        # for tmp in self.authors.all():
        #     ##name = tmp.name.encode('utf-8')
        #     name = tmp.name.encode('utf-8')
        #     print name
        #     authors.append(name)
        # return authors
        authors = ''
        for tmp in self.authors.all():
            authors  += ''.join(tmp.name) + ', '
        return authors

    authors_list.short_description = "authors all"

